package com.njupt.towerssystem.services.impl;

import com.google.common.hash.BloomFilter;
import com.njupt.towerssystem.config.SystemConfig;
import com.njupt.towerssystem.domain.ManagerInfos;
import com.njupt.towerssystem.mapper.ManageInfoMapper;
import com.njupt.towerssystem.services.RegisterUserService;
import lombok.Synchronized;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class RegisteUserServiceImpl implements RegisterUserService {

    @Resource
    private ManageInfoMapper manageInfoMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private BloomFilter<String> nameFilter;

    private ReentrantLock lock = new ReentrantLock();
    private static Queue<Integer> userids = new PriorityQueue<>();


    // 当springboot工程启动时候自动调用本方法对userids集合填充数据
    @PostConstruct // 当程序启动时自动启动本方法一次
    private void addNewUseridToArray() {
        int maxid = manageInfoMapper.findMaxUserid();
        for(int i = maxid;i<maxid+10000;i++){
            userids.add(i);
        }
    }

    // 程序启动将所有的用户名存放到bloom过滤器的bit数组中
    @PostConstruct
    private void addUserToBloom(){
        List<String> names = manageInfoMapper.findAllName();
        for (String name : names) {
            nameFilter.put(name);
        }
    }

    @Transactional
    @Override
    public boolean regUser(ManagerInfos mi) {
        // 到数据库检查用户名和密码是否存在 如果存在就gg
        // 通过布隆过滤器判断用户名是否存在 存在就直接返回false
        boolean isHas = nameFilter.mightContain(mi.getLoginname());
        if(isHas){
            return false;
        }
        //先查询最大的userid
        Integer maxid=0;
        lock.lock();
        try{
            if (userids.isEmpty()) {
                addNewUseridToArray();
            }
            maxid = userids.poll();
        } finally {
            lock.unlock();
        }
        // 先查询最大的userid
//        maxid = manageInfoMapper.findMaxUserid();
        // 将最大值填充到对象中
        mi.setUserid(maxid);
        // 将数据存放到数据库中
        manageInfoMapper.insertManagers(mi);
        stringRedisTemplate.opsForHash().
                put("mananges",mi.getLoginname()+mi.getLoginpwd(),mi.toString());

        // 将当前新建用户用户名存放到布隆过滤器中
        nameFilter.put(mi.getLoginname());
        return true;
    }
}
